package net.gyapp.markim.module.message;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.easyder.wrapper.core.model.BaseVo;
import com.easyder.wrapper.core.scheduler.Task;
import com.easyder.wrapper.core.scheduler.TaskScheduler;
import com.gyf.barlibrary.ImmersionBar;
import com.lqr.emoji.EmotionKeyboard;
import com.lqr.emoji.EmotionLayout;
import com.lqr.emoji.IEmotionExtClickListener;
import com.lqr.emoji.IEmotionSelectedListener;
import com.luck.picture.lib.PictureSelectionModel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.xuhao.android.libsocket.sdk.ConnectionInfo;
import com.xuhao.android.libsocket.utils.Logger;

import net.gyapp.markim.ApiConfig;
import net.gyapp.markim.R;
import net.gyapp.markim.core.IResult;
import net.gyapp.markim.core.ImHelper;
import net.gyapp.markim.core.ImManager;
import net.gyapp.markim.core.reponse.ImResponse;
import net.gyapp.markim.module.basic.base.CommonPresenter;
import net.gyapp.markim.module.basic.base.WrapperImActivity;
import net.gyapp.markim.module.message.adapter.ChatAdapter;
import net.gyapp.markim.module.message.bean.QiniuTokenVo;
import net.gyapp.markim.utils.SimpleTextWatcher;
import net.gyapp.markim.utils.libs.QiniuManager;
import net.gyapp.markim.widget.IndexRecyclerView;

import org.jim.common.packets.ChatType;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import me.winds.widget.usage.TitleView;

/**
 * Author:  winds
 * Data:    2018/7/18
 * Version: 1.0
 * Desc:
 */


public class ChatActivity extends WrapperImActivity<CommonPresenter> implements IEmotionSelectedListener {

    @BindView(R.id.mRecyclerView)
    IndexRecyclerView mRecyclerView;
    @BindView(R.id.iv_audio)
    ImageView ivAudio;
    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.btn_audio)
    Button btnAudio;
    @BindView(R.id.iv_emogi)
    ImageView ivEmogi;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.btn_send)
    Button btnSend;
    @BindView(R.id.layout_content)
    LinearLayout layoutContent;
    @BindView(R.id.el_emotion)
    EmotionLayout elEmotion;
    @BindView(R.id.ivAlbum)
    ImageView ivAlbum;
    @BindView(R.id.ivShot)
    ImageView ivShot;
    @BindView(R.id.ivLocation)
    ImageView ivLocation;
    @BindView(R.id.ivRedPack)
    ImageView ivRedPack;
    @BindView(R.id.layout_emotion)
    FrameLayout layoutEmotion;
    @BindView(R.id.layout_more)
    LinearLayout layoutMore;

    private String id;
    private String name;
    private String avatar;
    private ChatType chatType;
    private ChatAdapter adapter;
    private EmotionKeyboard mEmotionKeyboard;
    private QiniuTokenVo pictureToken;
    private QiniuTokenVo voiceToken;

    public static Intent getIntent(Context context) {
        return new Intent(context, ChatActivity.class);
    }

    /**
     * 群聊
     *
     * @param context
     * @param id
     * @return
     */
    public static Intent getIntent(Context context, String id, String name) {
        return new Intent(context, ChatActivity.class).putExtra("chatType", ChatType.CHAT_TYPE_PUBLIC.getNumber()).putExtra("id", id).putExtra("name", name);
    }

    /**
     * 私聊
     *
     * @param context
     * @param id
     * @param name
     * @param avatar
     * @return
     */
    public static Intent getIntent(Context context, String id, String name, String avatar) {
        return new Intent(context, ChatActivity.class).putExtra("chatType", ChatType.CHAT_TYPE_PRIVATE.getNumber())
                .putExtra("id", id)
                .putExtra("name", name)
                .putExtra("avatar", avatar);
    }

    @Override
    protected int getViewLayout() {
        return R.layout.activity_chat;
    }

    @Override
    protected void setImmersionBar() {
        super.setImmersionBar();
        ImmersionBar.with(this).keyboardEnable(true).init();
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        super.initView(savedInstanceState, titleView, intent);
        chatType = ChatType.valueOf(intent.getIntExtra("chatType", ChatType.CHAT_TYPE_UNKNOW.getNumber()));
        id = intent.getStringExtra("id");
        name = intent.getStringExtra("name");
        titleView.setCenterText(name);
        Logger.i("chatType " + chatType.toString());
        Logger.i("id " + id);
        if (chatType == ChatType.CHAT_TYPE_PRIVATE) {

            avatar = intent.getStringExtra("avatar");
        }
        setInterceptable(false);
        initEmotionKeyboard();
        initListener();
        initAdapter();
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        TaskScheduler.execute(new Task<List<ImResponse>>() {
            @Override
            public List<ImResponse> doInBackground() throws InterruptedException {
//                return ImHelper.getMessageList(id, 20);
                return new ArrayList<>();
            }

            @Override
            public void onSuccess(List<ImResponse> result) {
//                adapter.setAdapterData(result);
            }
        });
    }

    @Override
    public void showContentView(String url, BaseVo dataVo) {
        if (url.contains(ApiConfig.API_GET_PICTURE_TOKEN)) {
            pictureToken = (QiniuTokenVo) dataVo;
            uploadImage();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        etContent.clearFocus();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    obtainMediaResult(PictureSelector.obtainMultipleResult(data));
                    break;
            }
        }
    }


    @Override
    public void onBackPressedSupport() {
        if (elEmotion.isShown() || layoutMore.isShown()) {
            mEmotionKeyboard.interceptBackPress();
        } else {
            super.onBackPressedSupport();
        }
    }

    @Override
    public void onMessageReceive(Context context, ConnectionInfo info, String action, ImResponse response) {
        addAdapterData(response);
//        if (response instanceof ChatResponse) {
//            switch (chatType) {
//                case CHAT_TYPE_PUBLIC:
//                    ImHelper.updateOrInsertConversation(String.valueOf(id), name);
//                    break;
//            }
//            ImHelper.updateOrInsertMessage(response, Long.valueOf(id));
//        }
    }

    @OnClick({R.id.layout_album, R.id.layout_shot})
    void click(View view) {
        switch (view.getId()) {
            case R.id.layout_album:
                showPictureSelector();
                break;
        }
    }

    String path;

    private void obtainMediaResult(List<LocalMedia> localMedia) {
        if (localMedia != null && localMedia.size() > 0) {
            path = localMedia.get(0).getPath();
            upload(path);
        }
    }

    private void uploadImage() {
        if (!TextUtils.isEmpty(path)) {
            upload(path);
        }
    }


    private void upload(String path) {
        if (pictureToken != null) {
            QiniuManager.getInstance().getUploadManager().put(path, null, pictureToken.uptoken, new UpCompletionHandler() {
                @Override
                public void complete(String key, ResponseInfo info, JSONObject response) {
                    if (info.isOK()) {
                        Logger.i("key " + key);
                        Logger.i("info " + info.toString());
                        Logger.i("response " + response.toString());

                        try {
                            sendImageMessage(ImHelper.getActualPicturePath(response));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, null);
        } else {
            getPictureToken();
        }
    }

    private void getPictureToken() {
        presenter.setNeedDialog(false);
        presenter.postData(ApiConfig.API_GET_PICTURE_TOKEN, QiniuTokenVo.class);
    }

    /**
     * 初始化适配器
     */
    private void initAdapter() {
        adapter = new ChatAdapter();
        adapter.setChatType(chatType);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mRecyclerView.setAdapter(adapter);
    }

    /**
     * 添加数据
     *
     * @param response
     */
    private void addAdapterData(ImResponse response) {
        adapter.addAdapterData(response);
        mRecyclerView.smoothMoveToPosition(adapter.getItemCount() - 1);
    }


    private boolean sendTextMessage(String content) {
        Logger.i("content " + content);
        IResult result = null;
        switch (chatType) {
            case CHAT_TYPE_PUBLIC:
                result = ImManager.getInstance().sendLetterGroupMessage(ImHelper.getSelf(), ImHelper.getTimestamp(), id, content);
                break;
            case CHAT_TYPE_PRIVATE:
                result = ImManager.getInstance().sendLetterMessage(ImHelper.getSelf(), id, ImHelper.getTimestamp(), content);
//                ImHelper.updateOrInsertMessage(result.response, Long.valueOf(id));
                break;
        }
        if (result != null) {
            addAdapterData(result.response);
        }
        return result == null ? false : result.status;
    }

    private boolean sendImageMessage(String content) {
        IResult result = null;
        switch (chatType) {
            case CHAT_TYPE_PUBLIC:
                result = ImManager.getInstance().sendImageGroupMessage(ImHelper.getSelf(), ImHelper.getTimestamp(), id, content);
//                ImHelper.updateOrInsertConversation(String.valueOf(id), name);
                break;
            case CHAT_TYPE_PRIVATE:
                result = ImManager.getInstance().sendImageMessage(ImHelper.getSelf(), id, ImHelper.getTimestamp(), content);
//                ImHelper.updateOrInsertMessage(result.response, Long.valueOf(id));
                break;
        }
        if (result != null) {
            addAdapterData(result.response);
        }
        return false;
    }

    public void showPictureSelector() {
        showPictureSelector(1, true, true, false, false);
    }

    /**
     * 选取图片
     *
     * @param maxSelectNum 选取图片的数量  多选时才生效
     * @param singleMode   是否单选
     * @param showCamera   是否显示拍照按钮
     * @param crop         是否剪裁
     * @param isCircleMode 剪裁是否显示圆形参考   用于裁剪圆形头像    开启裁剪时生效
     */
    public void showPictureSelector(int maxSelectNum, boolean singleMode, boolean showCamera, boolean crop, boolean isCircleMode) {
        PictureSelectionModel model = PictureSelector.create(mActivity)
                .openGallery(PictureMimeType.ofImage()) //查看类型  仅图片,可选择其它或全部
                .theme(com.easyder.wrapper.R.style.picture_default_style)
                .maxSelectNum(maxSelectNum) //最大图片选择数量
                .imageSpanCount(4)// 每行显示个数
                .minSelectNum(1)// 最小选择数量
                .selectionMode(singleMode ?
                        PictureConfig.SINGLE : PictureConfig.MULTIPLE)// 单选 or 多选
                .isCamera(showCamera);// 是否显示拍照按钮


        if (crop) {
            model
                    .enableCrop(crop)             //开启裁剪
                    .hideBottomControls(false)  //是否隐藏裁剪工具栏
                    .circleDimmedLayer(isCircleMode)    //显示圆形参考图层
                    .withAspectRatio(1, 1);     //裁剪比例
        }
        model.forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
    }

    /***********************************************************************************************/
    @Override
    public void onEmojiSelected(String key) {

    }

    @Override
    public void onStickerSelected(String categoryName, String stickerName, String stickerBitmapPath) {

    }


    public void initListener() {
        elEmotion.setEmotionSelectedListener(this);
        elEmotion.setEmotionAddVisiable(true);
        elEmotion.setEmotionSettingVisiable(true);
        elEmotion.setEmotionExtClickListener(new IEmotionExtClickListener() {
            @Override
            public void onEmotionAddClick(View view) {
                Toast.makeText(getApplicationContext(), "add", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEmotionSettingClick(View view) {
                Toast.makeText(getApplicationContext(), "setting", Toast.LENGTH_SHORT).show();
            }
        });
        layoutContent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        closeBottomAndKeyboard();
                        break;
                }
                return false;
            }
        });
        ivAudio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (btnAudio.isShown()) {
                    hideAudioButton();
                    etContent.requestFocus();
                    if (mEmotionKeyboard != null) {
                        mEmotionKeyboard.showSoftInput();
                    }
                } else {
                    showAudioButton();
                    hideEmotionLayout();
                    hideMoreLayout();
                }
            }
        });
        etContent.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (etContent.getText().toString().trim().length() > 0) {
                    btnSend.setVisibility(View.VISIBLE);
                    ivMore.setVisibility(View.GONE);
                } else {
                    btnSend.setVisibility(View.GONE);
                    ivMore.setVisibility(View.VISIBLE);
                }
            }


        });
        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = etContent.getText().toString();
                if (!TextUtils.isEmpty(content)) {
                    if (sendTextMessage(content)) {
                        etContent.setText("");
                    }
                }

            }
        });
    }

    private void initEmotionKeyboard() {
        elEmotion.attachEditText(etContent);
        mEmotionKeyboard = EmotionKeyboard.with(this);
        mEmotionKeyboard.bindToEditText(etContent);
        mEmotionKeyboard.bindToContent(layoutContent);
        mEmotionKeyboard.setEmotionLayout(layoutEmotion);
        mEmotionKeyboard.bindToEmotionButton(ivEmogi, ivMore);
        mEmotionKeyboard.setOnEmotionButtonOnClickListener(new EmotionKeyboard.OnEmotionButtonOnClickListener() {
            @Override
            public boolean onEmotionButtonOnClickListener(View view) {
                switch (view.getId()) {
                    case R.id.iv_emogi:
                        if (!elEmotion.isShown()) {
                            if (layoutMore.isShown()) {
                                showEmotionLayout();
                                hideMoreLayout();
                                hideAudioButton();
                                return true;
                            }
                        } else if (elEmotion.isShown() && !layoutMore.isShown()) {
                            ivEmogi.setImageResource(R.drawable.ic_cheat_emo);
                            return false;
                        }
                        showEmotionLayout();
                        hideMoreLayout();
                        hideAudioButton();
                        break;
                    case R.id.iv_more:
                        if (!layoutMore.isShown()) {
                            if (elEmotion.isShown()) {
                                showMoreLayout();
                                hideEmotionLayout();
                                hideAudioButton();
                                return true;
                            }
                        }
                        showMoreLayout();
                        hideEmotionLayout();
                        hideAudioButton();
                        break;
                }
                return false;
            }
        });
    }


    private void showAudioButton() {
        btnAudio.setVisibility(View.VISIBLE);
        etContent.setVisibility(View.GONE);
        ivAudio.setImageResource(R.drawable.ic_cheat_keyboard);

        if (layoutEmotion.isShown()) {
            if (mEmotionKeyboard != null) {
                mEmotionKeyboard.interceptBackPress();
            }
        } else {
            if (mEmotionKeyboard != null) {
                mEmotionKeyboard.hideSoftInput();
            }
        }
    }

    private void hideAudioButton() {
        btnAudio.setVisibility(View.GONE);
        etContent.setVisibility(View.VISIBLE);
        ivAudio.setImageResource(R.drawable.ic_cheat_voice);
    }

    private void showEmotionLayout() {
        elEmotion.setVisibility(View.VISIBLE);
        ivEmogi.setImageResource(R.drawable.ic_cheat_keyboard);
    }

    private void hideEmotionLayout() {
        elEmotion.setVisibility(View.GONE);
        ivEmogi.setImageResource(R.drawable.ic_cheat_emo);
    }

    private void showMoreLayout() {
        layoutMore.setVisibility(View.VISIBLE);
    }

    private void hideMoreLayout() {
        layoutMore.setVisibility(View.GONE);
    }

    private void closeBottomAndKeyboard() {
        elEmotion.setVisibility(View.GONE);
        layoutMore.setVisibility(View.GONE);
        if (mEmotionKeyboard != null) {
            mEmotionKeyboard.interceptBackPress();
        }
    }
    /***********************************************************************************************/
}
